<!-- 学校banner -->
<template>
  <div class="content_box">
    <div class="sbanner_header sbFlex">
      <div class="sbanner_header_l">可拖拽banner排序</div>
      <div class="cenFlex">
        <el-select
          v-model="bannerArrStatus"
          size="small"
          style="margin-right: 10px"
          clearable
          placeholder="请选择"
        >
          <el-option label="全部" value=""> </el-option>
          <el-option label="已启用" value="1"> </el-option>
          <el-option label="已禁用" value="2"> </el-option>
        </el-select>
        <el-button
          class="sbanner_header_button"
          type="primary"
          size="small"
          @click="seeImgUrlFn"
          >预览</el-button
        >
        <el-button
          class="sbanner_header_button"
          type="primary"
          size="small"
          @click="bannerAddFormVisible = true"
          >新增banner</el-button
        >
      </div>
    </div>
    <draggable
      v-if="bannerArr[0]"
      v-model="bannerArr"
      @end="end"
      v-bind="posterOptions"
      class="sbanner"
    >
      <!-- <div class="dis_sbanner_box_ cenFlex">
        <div class="sbanner_updata_box_in cenFlex">
          <div class="sbanner_updata_box_in_in">
            <div class="sbanner_updata_box_in_in_t cenFlex">+</div>
            <div class="sbanner_updata_box_in_in_b">创建</div>
          </div>
        </div>
      </div> -->
      <div
        :class="item.status == 1 ? 'sbanner_box' : 'dis_sbanner_box_'"
        v-for="(item, ix) in bannerArr"
        :key="ix + '11'"
      >
        <div class="sbanner_box_img cenFlex">
          <img :src="item.imageUrl" alt="" />
        </div>
        <div class="sbanner_box_title">{{ item.title }}</div>
        <div
          class="sbanner_box_btn cenFlex tr"
          v-if="item.status == 1"
          @click="statusFn(item.id, 2)"
        >
          禁用
        </div>
        <div class="sbanner_box_btn cenFlex" v-else>
          <div class="sbanner_box_btn_in tl cenFlex" @click="delDataFn(item)">
            删除
          </div>
          <div
            :style="{ color: item.status == 1 ? '#999999' : '#0066fa' }"
            class="sbanner_box_btn_in tr cenFlex"
            @click="statusFn(item.id, item.status == 1 ? 2 : 1)"
          >
            {{ item.status == 1 ? '禁用' : '启用' }}
          </div>
        </div>
      </div>
    </draggable>
    <el-dialog
      title="创建"
      center
      :visible.sync="bannerAddFormVisible"
      width="740px"
    >
      <el-form :model="bannerAdd" label-width="100px" label-position="right">
        <el-form-item label="标题">
          <el-input
            v-model="bannerAdd.title"
            autocomplete="off"
            maxlength="50"
            style="width: 480px"
          ></el-input>
        </el-form-item>
        <el-form-item label="" v-if="bannerAdd.imageUrl">
          <div class="bannerAddimgUrl cenFlex">
            <img :src="bannerAdd.imageUrl" alt="" />
            <div class="bannerAddimgUrl_del" @click="bannerAdd.imageUrl = ''">
              <i class="el-icon-delete"></i>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="" v-else>
          <div
            class="cenFlex tuozhuai_out"
            @dragover="fileDragover"
            @drop="fileDrop"
          >
            <div class="tuozhuai">
              <div class="tuozhuai_img">
                <img src="../../../../assets/img/icon_img.png" alt="" />
              </div>
              <div class="tuozhuai_btn cenFlex">
                <updateFile
                  updata-id="inputName"
                  @updata="file => uploadImg(file[0].files)"
                />添加图片
              </div>
              <div class="tuozhuai_txt">
                规格1280*480，支持png、jpg,拖拽上传
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="bannerAddFormVisible = false"
          style="margin-right: 32px"
          >取 消</el-button
        >
        <el-button type="primary" @click="okDataFn">完 成</el-button>
      </div>
    </el-dialog>
    <el-dialog
      custom-class="bannerArrImg_out"
      style="background: transparent"
      :visible.sync="seeImgUrlFlage"
      width="1000px"
      :show-close="false"
      trigger="click"
    >
      <el-carousel height="360px" v-if="bannerArr1[0]">
        <div class="bannerArrImg_close cenFlex" @click="seeImgUrlFlage = false">
          <img src="../../../../assets/img/icon_close.png" alt="" />
        </div>
        <el-carousel-item v-for="(item, ix) in bannerArr1" :key="ix">
          <div class="bannerArrImg cenFlex">
            <img :src="item.imageUrl" alt="" />
          </div>
        </el-carousel-item>
      </el-carousel>
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { ossUpload } from '@/api/api.js'
import {
  adminschoolbanneradd,
  adminschoolbannerupdateStatus,
  adminschoolbannersort,
  adminschoolbannerdelete,
  adminschoolbannerlist
} from '@/api/user.js'
export default {
  name: 'school-banner',
  components: {
    draggable,
    updateFile: resolve => require(['@/components/updateFile.vue'], resolve)
  },
  data () {
    return {
      bannerArrAll: [],
      bannerArr: [],
      bannerArr1: [],
      posterOptions: { draggable: '.sbanner_box' },
      bannerAdd: {
        schoolId: this.$route.query.id, // 学校ID
        title: '', // 标题
        imageUrl: '', // banner图片地址
        sortNo: 1 // 序号
      },
      bannerAddFormVisible: false,
      seeImgUrl: '',
      seeImgUrlFlage: false,
      bannerArrStatus: ''
    }
  },
  watch: {
    bannerArrStatus (val) {
      let bannerArrAll = this.bannerArrAll
      if (val == 1) {
        this.bannerArr = bannerArrAll
          .map(item => (item.status == 1 ? item : false))
          .filter(item => item)
      } else if (val == 2) {
        this.bannerArr = bannerArrAll
          .map(item => (item.status == 2 ? item : false))
          .filter(item => item)
      } else {
        this.bannerArr = this.bannerArrAll
      }
      this.bannerArr.splice(1, 0)
      this.forDataArrFn()
    }
  },
  // 生命周期 - 创建完成（访问当前this实例）
  activated () {
    this.bannerAdd.schoolId = this.$route.query.id
    this.getListFn()
  },
  methods: {
    async end (e) {
      let _obj = this.bannerArr.map((item, ix) => {
        return { id: item.id, sortNo: ix + 1 }
      })
      let res = await adminschoolbannersort(_obj)
      if (res[0]) {

      }
    },
    // 拖拽的方法
    fileDragover (e) {
      e.preventDefault()
    },
    fileDrop (e) {
      e.preventDefault()

      const file = e.dataTransfer.files[0] // 获取到第一个上传的文件对象
      const url = this.getObjectURL(file)
      this.batchFile = file
      this.fileName = file.name
      this.updataImgFlag = false

      this.uploadImg(file)
      document.getElementById('inputName').value = ''
    },
    // 获取base64
    getObjectURL (file) {
      var url = null
      if (window.createObjectURL != undefined) {
        // basic
        url = window.createObjectURL(file)
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        url = window.URL.createObjectURL(file)
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        url = window.webkitURL.createObjectURL(file)
      }
      return url
    },
    // 点击预览
    seeImgUrlFn () {
      let bannerArr = this.bannerArr
      this.bannerArr1 = bannerArr
        .map(item => (item.status == 1 ? item : false))
        .filter(item => item)
      this.bannerArr1.splice(1, 0)
      this.seeImgUrlFlage = true
    },
    // 点击查看预览图片
    imgSee (imgUrl) {
      this.seeImgUrl = imgUrl
      this.seeImgUrlFlage = true
    },
    // 点击删除数据
    async delDataFn (item) {
      if (item.status == 1) {
        this.$alert('当前是启用状态，请禁用后删除', '删除', {
          confirmButtonText: '确定',
          confirmButtonClass: 'confirmButtonClass',
          center: true,
          callback: action => {}
        })
        return
      }
      this.$confirm('是否删除当前项目，删除后无法恢复', '删除', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        cancelButtonClass: 'cancelButtonClass',
        confirmButtonClass: 'confirmButtonClass',
        customClass: 'confirmcustomClass',
        center: true
      })
        .then(async () => {
          let res = await adminschoolbannerdelete({ id: item.id })
          if (res[0]) {
            return
          }
          this.$message.success('删除成功')
          this.bannerAdd = {
            schoolId: this.bannerAdd.schoolId, // 学校ID
            title: '', // 标题
            imageUrl: '', // banner图片地址
            sortNo: 1 // 序号
          }
          this.bannerAddFormVisible = false
          this.getListFn()
        })
        .catch(() => {})
    },
    // 初始获取banner的列表
    async getListFn () {
      this.bannerArr = []
      let res = await adminschoolbannerlist({
        schoolId: this.bannerAdd.schoolId
      })
      if (res[0]) {
        return
      }
      let bannerArrAll = res[1].data
      this.bannerArrAll = bannerArrAll
      if (this.bannerArrStatus == 1) {
        this.bannerArr = bannerArrAll
          .map(item => (item.status == 1 ? item : false))
          .filter(item => item)
      } else if (this.bannerArrStatus == 2) {
        this.bannerArr = bannerArrAll
          .map(item => (item.status == 2 ? item : false))
          .filter(item => item)
      } else {
        this.bannerArr = bannerArrAll
      }
      this.forDataArrFn()
    },
    async uploadImg (file) {
      console.log(file)
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式或 GIF 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return
      }
      let formData = new FormData()
      formData.append('file', file)
      let res = await ossUpload(formData, 'SCHOOL_BANNER')
      if (res[0]) {
        return
      }
      this.bannerAdd.imageUrl = res[1].data.url
    },
    // 点击确认当前数据
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async statusFn (id, status) {
      let res = await adminschoolbannerupdateStatus({
        id,
        status
      })
      if (res[0]) {
        return
      }
      this.$message.success('状态修改成功')
      this.getListFn()
    },
    // 循环当前的数组将禁用放到后面
    async forDataArrFn () {
      let arr = []
      let arrEnd = []
      this.bannerArr.map(item => {
        if (item.status == 1) {
          arr.push(item)
        } else {
          arrEnd.push(item)
        }
      })
      arr = [...arr, ...arrEnd]
      this.bannerArr = arr
      this.bannerArr.splice(1, 0)
    },
    handleAdd (obj) {},
    // 点击提交新增
    async okDataFn () {
      let res = await adminschoolbanneradd(this.bannerAdd)
      if (res[0]) {
        return
      }
      this.$message.success('添加成功')
      this.bannerAdd = {
        schoolId: this.bannerAdd.schoolId, // 学校ID
        title: '', // 标题
        imageUrl: '', // banner图片地址
        sortNo: 1 // 序号
      }
      this.bannerAddFormVisible = false
      this.$nextTick(() => {
        this.getListFn()
      })
    }
  }
}
</script>
<style lang="scss">
.bannerArrImg_out {
  background: transparent;
  box-shadow: 0px 0px 0px transparent;
  .bannerArrImg_close {
    width: 46px;
    height: 46px;
    background: rgba($color: #000000, $alpha: 0.2);
    border-radius: 50%;
    position: absolute;
    z-index: 999;
    right: 15px;
    top: 15px;
    img {
      width: 18px;
    }
  }
  .el-carousel__indicators {
    // 指示器
    // left: unset;
    // transform: unset;
    // right: 2%;
  }
  .el-carousel__button {
    // 指示器按钮
    width: 10px;
    height: 10px;
    border: none;
    border-radius: 50%;
    background-color: #8d8d8d;
  }
  .is-active .el-carousel__button {
    // 指示器激活按钮
    background: #e0e0e0;
  }
}
.sbanner {
  display: flex;
  flex-wrap: wrap;
}
.sbanner_header {
  width: 100%;
  margin-bottom: 18px;
  .sbanner_header_l {
    color: #999;
  }
}
.bannerArrImg {
  width: 960px;
  height: 360px;
  img {
    width: 100%;
  }
}
.bannerAddimgUrl {
  width: 480px;
  height: 180px;
  overflow: hidden;
  position: relative;
  border: 1px solid #bdbdbd;
  img {
    width: 100%;
  }
}
.bannerAddimgUrl_del {
  position: absolute;
  bottom: 0px;
  right: 0px;
  i {
    color: #f86561;
    font-size: 30px;
  }
}
.sbanner_box,
.dis_sbanner_box_ {
  width: 456px;
  height: 250px;
  margin-right: 20px;
  margin-bottom: 20px;
  .sbanner_updata_box_in {
    width: 456px;
    height: 171px;
    img {
      width: 100%;
    }
    .sbanner_updata_box_in_in_t {
      text-align: center;
      font-size: 40px;
    }
  }
  .sbanner_box_img {
    width: 100%;
    height: 171px;
    overflow: hidden;
    img {
      width: 100%;
    }
  }

  .sbanner_box_title {
    width: 100%;
    margin: 13px 0px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .sbanner_box_btn {
    width: 220px;
    height: 32px;
    background: #e9e9e9;
    margin: 0px auto;
    border-radius: 0px 0px 5px 5px;
    border: 1px solid #d8d8d8;
    .sbanner_box_btn_in {
      width: 100%;
      cursor: pointer;
    }
  }
  .tl {
    color: #f86561;
    border-right: 1px #d8d8d8 solid;
  }
  .tr {
    color: #0066fa;
  }
}
.upload-demo {
  width: 500px;
}
.confirmcustomClass {
  width: 390px;
}
.el-message-box__btns {
  margin-top: 73px;
}
.el-upload-dragger {
  width: 500px !important;
}
.cancelButtonClass {
  margin-right: 32px;
  min-width: 86px;
}
.confirmButtonClass {
  min-width: 86px;
}
.tuozhuai_out {
  width: 480px;
  height: 180px;
  border: 1px dashed #999;
  .tuozhuai_img {
    width: 32px;
    height: 35px;
    margin: 0px auto;
    margin-bottom: 16px;
    img {
      width: 100%;
    }
  }
  .tuozhuai_btn {
    position: relative;
    margin: 0px auto;
    width: 100px;
    height: 32px;
    background: #ffffff;
    border-radius: 2px;
    border: 1px solid #d9d9d9;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
    line-height: 16px;
  }
  .tuozhuai_txt {
    margin: 0px auto;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #666666;
    line-height: 12px;
    margin-top: 15px;
  }
}
</style>
